package 链表.单链表;

/**
 * https://leetcode.cn/problems/intersection-of-two-linked-lists/description/?envType=study-plan-v2&envId=top-100-liked
 *
 * https://leetcode.cn/problems/intersection-of-two-linked-lists/?favorite=2cktkvj
 */
public class _160_相交链表 {

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        // p1 指向 A 链表头结点，p2 指向 B 链表头结点
        ListNode p1 = headA;
        ListNode p2 = headB;

        while (p1 != p2) {
            // p1 走一步，如果走到 A 链表末尾，转到 B 链表
            if(p1 != null) {
                p1 = p1.next;
            }else {
                p1 = headB;
            }

            // p2 走一步，如果走到 B 链表末尾，转到 A 链表
            if(p2 != null){
                p2 = p2.next;
            }else {
                p2 = headA;
            }
        }

        return p1;
    }
}
